export interface LrcLine {
  time: number; // 时间戳（秒）
  text: string; // 歌词文本
  originalTime: string; // 原始时间格式
}

export interface ParsedLrc {
  lines: LrcLine[];
  title?: string;
  artist?: string;
  album?: string;
}

/**
 * 解析时间戳 [mm:ss.xx] 格式
 */
function parseTimeStamp(timeStr: string): number {
  const match = timeStr.match(/\[(\d{2}):(\d{2})\.(\d{2})\]/);
  if (!match) return 0;
  
  const minutes = parseInt(match[1], 10);
  const seconds = parseInt(match[2], 10);
  const centiseconds = parseInt(match[3], 10);
  
  return minutes * 60 + seconds + centiseconds / 100;
}

/**
 * 解析LRC文件内容
 */
export function parseLrc(lrcContent: string): ParsedLrc {
  const lines = lrcContent.split('\n');
  const lrcLines: LrcLine[] = [];
  const metadata: any = {};
  
  for (const line of lines) {
    const trimmedLine = line.trim();
    if (!trimmedLine) continue;
    
    // 解析元数据
    const metaMatch = trimmedLine.match(/\[(\w+):(.+)\]/);
    if (metaMatch && !metaMatch[1].match(/\d/)) {
      metadata[metaMatch[1]] = metaMatch[2];
      continue;
    }
    
    // 解析时间戳和歌词
    const timeMatch = trimmedLine.match(/\[(\d{2}:\d{2}\.\d{2})\](.*)$/);
    if (timeMatch) {
      const time = parseTimeStamp(`[${timeMatch[1]}]`);
      const text = timeMatch[2].trim();
      
      if (text) { // 只添加有文本的行
        lrcLines.push({
          time,
          text,
          originalTime: timeMatch[1]
        });
      }
    }
  }
  
  // 按时间排序
  lrcLines.sort((a, b) => a.time - b.time);
  
  return {
    lines: lrcLines,
    title: metadata.ti,
    artist: metadata.ar,
    album: metadata.al
  };
}

/**
 * 根据当前播放时间获取当前应该显示的歌词行索引
 */
export function getCurrentLrcIndex(lrcLines: LrcLine[], currentTime: number): number {
  if (lrcLines.length === 0) return -1;
  
  for (let i = lrcLines.length - 1; i >= 0; i--) {
    if (currentTime >= lrcLines[i].time) {
      return i;
    }
  }
  
  return -1;
}

/**
 * 格式化时间显示
 */
export function formatTime(seconds: number): string {
  const mins = Math.floor(seconds / 60);
  const secs = Math.floor(seconds % 60);
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}